package me.minecraft.mod.cobblemonbukkitevent.mixin;

import com.cobblemon.mod.common.Cobblemon;
import com.cobblemon.mod.common.api.battles.model.PokemonBattle;
import com.cobblemon.mod.common.api.moves.MoveTemplate;
import com.cobblemon.mod.common.battles.interpreter.instructions.MoveInstruction;
import com.cobblemon.mod.common.battles.pokemon.BattlePokemon;
import me.minecraft.mod.cobblemonbukkitevent.bukkit.EventFactory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.lang.reflect.Field;

/**
 * @author langle__
 * @version 1.0
 */
@Mixin(value = MoveInstruction.class, remap = false)
public class MoveInstructionMixin {

    @Inject(method = "invoke", at = @At("HEAD"))
    public void invoke(PokemonBattle battle, CallbackInfo ci) {
        try {
            MoveInstruction instruction = (MoveInstruction) (Object) this;
            Field userPokemonField = MoveInstruction.class.getDeclaredField("userPokemon");
            userPokemonField.setAccessible(true);
            BattlePokemon userPokemon = (BattlePokemon) userPokemonField.get(instruction);
            Field targetPokemonField = MoveInstruction.class.getDeclaredField("targetPokemon");
            targetPokemonField.setAccessible(true);
            BattlePokemon targetPokemon = (BattlePokemon) targetPokemonField.get(instruction);
            Field moveField = MoveInstruction.class.getDeclaredField("move");
            moveField.setAccessible(true);
            MoveTemplate moveTemplate = (MoveTemplate) moveField.get(instruction);
            EventFactory.callMoveUsedEvent(battle, userPokemon, targetPokemon, moveTemplate);
        } catch (Exception e) {
            Cobblemon.LOGGER.error("Error in MoveInstructionMixin (usage): ", e);
        }
    }

}
